package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;


@Slf4j
@RestController  // ResponseBody+Controller  ResponseBody:将字符串转成JSON
@RequestMapping("/employee")
@SuppressWarnings(value = "all")//抑制所有警告
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;

    /**
     * 员工登录
     * @param request
     * @param employee
     * @return
     */
    @PostMapping("/login")//request 获取session 将用户存入session中
    public R<Employee> login(HttpServletRequest request, @RequestBody Employee employee){
        //1.获取前端传来的密码  需要加密
        String password = employee.getPassword();
        password=DigestUtils.md5DigestAsHex(password.getBytes());

        //2.根据用户名查询密码
        LambdaQueryWrapper<Employee> wrapper=new LambdaQueryWrapper<>();
        //查询条件是
        wrapper.eq(Employee::getUsername,employee.getUsername());
        //查询结果
        Employee emp = employeeService.getOne(wrapper);

        //判断用户是否存在
        if(emp==null){
            return R.error("用户不存在,请检查用户名!");
        }

        //3.判断密码是否正确
        if(!emp.getPassword().equals(password)){
            return R.error("用户名或密码不正确!");
        }

        //判断是否启用
        if(emp.getStatus()==0){
            return R.error("用户已禁用!");
        }

        //4.比对成功 存入session中 并返回对象  不返回密码
        request.getSession().setAttribute("employee",emp.getId());
        emp.setPassword("");

        return R.success(emp);
    }

    /**
     * 员工退出
     * @param request
     * @return
     */
    @PostMapping("/logout")
    public R<String> logout(HttpServletRequest request){
        //清理Session中保存的当前登录员工的id
        request.getSession().removeAttribute("employee");
        return R.success("退出成功");
    }

    /**
     * 添加员工
     * @param employee
     * @return
     */
    @PostMapping
    public R<String> save(HttpServletRequest request,@RequestBody Employee employee){
        log.info("添加的员工信息:{}",employee.toString());

        //1.设置员工初始密码 需要使用MD5 加密
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));

        //2.设置createTime updateTime
        /*employee.setCreateTime(LocalDateTime.now());
        employee.setUpdateTime(LocalDateTime.now());*/

        //3.设置createUser, updateUser
        /*long empId = (long) request.getSession().getAttribute("employee");
        employee.setCreateUser(empId);
        employee.setUpdateUser(empId);*/

        employeeService.save(employee);
//SQLIntegrityConstraintViolationException: Duplicate entry 'zhangsan' for key 'idx_username' 异常
        //返回数据
        return R.success("添加成功");
    }

    /**
     * 员工分页条件查询
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page,int pageSize,String name){
        log.info("page={},pageSize={},name={}",page,pageSize,name);

        //构造分页条件  mp内置的
        Page pageInfo=new Page(page,pageSize);

        //条件查询
        LambdaQueryWrapper<Employee> wrapper=new LambdaQueryWrapper<Employee>();

        //使用common提供的工具类对 name 进行非空判断
        wrapper.like(StringUtils.isNotEmpty(name),Employee::getName,name);//相当于 where name={name}

        //构建排序条件 更新时间倒序排序
        wrapper.orderByDesc(Employee::getCreateTime);

        //查询                分页条件  查询条件
        employeeService.page(pageInfo,wrapper);

        //执行成功后  需要返回给页面的数据total records
        // 数据在page中储存   所以返回pageInfo
        return R.success(pageInfo);
    }

    /**
     * 根据id修改员工信息
     * @param request
     * @param employee
     * @return
     */
    @PutMapping
    public R<String> update(HttpServletRequest request,@RequestBody Employee employee){
        log.info(employee.toString());
        //修改者的id
        //Long empId = (Long) request.getSession().getAttribute("employee");

        /*employee.setUpdateTime(LocalDateTime.now());
        employee.setUpdateUser(empId)*/;

        //这里修改并不能成功 因为js只能处理16位的数字而id是18位 所以会出现精度丢失问题
        //需要自定义类型转换器 将long类型转成字符串类型 响应给前端
        employeeService.updateById(employee);
        return R.success("修改成功");
    }

    @GetMapping("/{id}")
    public R<Employee> getById(@PathVariable Long id){
        log.info("根据id查询员工信息...");

        Employee employee = employeeService.getById(id);
        //判断是否有该员工
        if(employee !=null){
            return R.success(employee);
        }
        return R.error("没有查询到该员工");
    }
}
